<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoles">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="rolesList" stripe style="width: 100%" border>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 一级 -->
            <el-row
              v-for="(item1,index1) in scope.row.children"
              :key="item1.id"
              :class="['botborder','ycenter',index1==0?'topborder':'']"
            >
              <el-col :span="5">
                <el-tag closable @close="removeRights(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级 -->
              <el-col :span="19">
                <!-- 二级 -->
                <el-row
                  v-for="(item2,index2) in item1.children"
                  :key="item2.id"
                  :class="['ycenter',index2!==0?'topborder':'']"
                >
                  <el-col :span="8">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRights(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="16">
                    <!-- 三级 -->
                    <el-tag
                      style="margin-right:10px"
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRights(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editRolesInfo(scope.row.id)"
            >编辑</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteRoles(scope.row.id)"
            >删除</el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="AssignPermissions(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 权限分配对话框 -->
    <!-- 头部提示信息 -->
    <el-dialog
      title="分配权限"
      :visible.sync="dialogVisibleAssign"
      width="50%"
      @closed="closedAssignDialog"
    >
      <!-- 主体内容 -->
      <el-tree
        ref="tree"
        :data="AssignList"
        :props="treeProps"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="arr"
      ></el-tree>
      <!-- 底部按钮 -->
      <span slot="footer">
        <el-button @click="dialogVisibleAssign = false">取 消</el-button>
        <el-button type="primary" @click="sureAssign">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加角色弹窗 -->
    <!-- 头部提示信息 -->
    <el-dialog
      title="添加角色"
      :visible.sync="dialogVisibleAddRoles"
      width="50%"
      @closed="closedAddRoles"
    >
      <!-- 主体内容 -->
      <el-form :model="addRolesForm" :rules="addRolesRules" label-width="100px" ref="addRolesRef">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer">
        <el-button @click="dialogVisibleAddRoles = false">取 消</el-button>
        <el-button type="primary" @click="sureAddRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色弹窗 -->
    <!-- 头部提示信息 -->
    <el-dialog title="修改角色" :visible.sync="dialogVisibleEditRoles" width="50%">
      <!-- 主体内容 -->
      <el-form
        :model="editRolesForm"
        :rules="editRolesRules"
        label-width="100px"
        ref="editRolesRef"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer">
        <el-button @click="dialogVisibleEditRoles = false">取 消</el-button>
        <el-button type="primary" @click="sureEditRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //编辑用户表单
      editRolesForm: {
        roleId: "",
        roleName: "",
        roleDesc: "",
      },
      //编辑用户表单验证规则
      editRolesRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
      },
      //编辑对话框隐藏与否
      dialogVisibleEditRoles: false,
      //添加用户表单
      addRolesForm: {
        roleName: "",
        roleDesc: "",
      },
      //添加用户表单验证规则
      addRolesRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
      },
      //添加绝色弹窗显示与否
      dialogVisibleAddRoles: false,
      // 所有角色列表数据
      rolesList: [],
      //   权限分配弹窗显示与否
      dialogVisibleAssign: false,
      //   权限请求数据
      AssignList: [],
      //树形组件配置参数
      treeProps: {
        label: "authName",
        children: "children",
      },
      //   默认选中权限id数组
      arr: [],
      //即将分配的权限id
      assingId: "",
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.axios.get("roles");
      if (res.meta.status !== 200) {
        return layer.msg(res.meta.msg, { time: 1000 });
      }
      this.rolesList = res.data;
    },
    removeRights(roles, rightId) {
      layer.confirm(
        "此操作将永久删除该权限, 是否继续?",
        { icon: 3, title: "提示" },
        async (index) => {
          const { data: res } = await this.axios.delete(
            `roles/${roles.id}/rights/${rightId}`
          );
          if (res.meta.status !== 200) {
            return layer.msg(res.meta.msg, { time: 1000 });
          }
          layer.msg(res.meta.msg, { time: 1000 }, () => {
            roles.children = res.data;
            layer.close(index);
          });
        }
      );
    },
    // 权限分配按钮
    async AssignPermissions(roles) {
      this.assingId = roles.id;
      const { data: res } = await this.axios.get("rights/tree");
      if (res.meta.status !== 200) {
        return layer.msg(res.meta.msg, { time: 1000 });
      }
      this.AssignList = res.data;
      this.getId(roles, this.arr);
      this.dialogVisibleAssign = true;
    },
    //确定分配按钮
    async sureAssign() {
      // 准备请求数据
      const key = [
        ...this.$refs.tree.getCheckedKeys(),
        ...this.$refs.tree.getHalfCheckedKeys(),
      ];
      const str = key.join(",");
      //   发起请求
      const {
        data: res,
      } = await this.axios.post(`roles/${this.assingId}/rights`, { rids: str });
      if (res.meta.status != 200) {
        return layer.msg(res.meta.msg, { time: 1000 });
      }
      layer.msg("分配成功！", { time: 1000 });
      this.getRolesList();
      this.dialogVisibleAssign = false;
    },
    //递归获取3级节点的id保存到数组中
    getId(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => {
        this.getId(item, arr);
      });
    },
    //监听权限分配对话框关闭
    closedAssignDialog() {
      this.arr = [];
    },
    // 点击添加按钮
    addRoles() {
      this.dialogVisibleAddRoles = true;
    },
    // 关闭添加按钮弹窗回调  清空表单
    closedAddRoles() {
      this.$refs.addRolesRef.resetFields();
    },
    //确定添加按钮
    sureAddRoles() {
      this.$refs.addRolesRef.validate(async (value) => {
        if (!value) {
          return layer.msg("您输入不正确，请重新输入！", { time: 1000 });
        }
        const { data: res } = await this.axios.post("roles", this.addRolesForm);
        if (res.meta.status !== 201) {
          return layer.msg(res.meta.msg, { time: 1000 });
        }
        layer.msg(res.meta.msg, { time: 1000 }, () => {
          this.getRolesList();
          this.dialogVisibleAddRoles = false;
        });
      });
    },
    //删除按钮
    deleteRoles(id) {
      layer.confirm(
        "此操作将永久删除该角色, 是否继续?",
        { icon: 3, title: "提示" },
        async (index) => {
          const { data: res } = await this.axios.delete("roles/" + id);
          if (res.meta.status !== 200) {
            return layer.msg(res.meta.msg, { time: 1000 });
          }
          layer.msg(res.meta.msg, { time: 1000 }, () => {
            this.getRolesList();
            layer.close(index);
          });
        }
      );
    },
    //编辑用户
    async editRolesInfo(id) {
      this.dialogVisibleEditRoles = true;
      const { data: res } = await this.axios.get("roles/" + id);
      if (res.meta.status !== 200) {
        return layer.msg(res.meta.msg, { time: 1000 });
      }
      this.editRolesForm.roleId = res.data.roleId;
      this.editRolesForm.roleName = res.data.roleName;
      this.editRolesForm.roleDesc = res.data.roleDesc;
    },
    //确定编辑按钮
    async sureEditRoles() {
      const { data: res } = await this.axios.put(
        "roles/" + this.editRolesForm.roleId,
        {
          roleName: this.editRolesForm.roleName,
          roleDesc: this.editRolesForm.roleDesc,
        }
      );
      if (res.meta.status !== 200) {
        return layer.msg(res.meta.msg, { time: 1000 });
      }
      layer.msg("修改成功！", { time: 1000 }, () => {
        this.getRolesList();
        this.dialogVisibleEditRoles = false;
      });
    },
  },
};
</script>

<style>
.topborder {
  border-top: 1px solid #ebeef5;
}
.botborder {
  border-bottom: 1px solid #ebeef5;
}
.el-tag {
  margin: 10px 0px;
}
.ycenter {
  display: flex;
  align-items: center;
}
</style>